from django.shortcuts import render,HttpResponse, redirect
from app_user.models import Order,Goods,sales_data
from alipay import AliPay, DCAliPay, ISVAliPay
from alipay.utils import AliPayConfig
from datetime import datetime



"""
商家账户： gaexwq7830@sandbox.com
买家账户： imtfvj7972@sandbox.com
密码： 1111111
"""

def alipay(request, oid):
    """"""
    """支付"""

    app_private_key_string = open("cert/ali_private_key.pem").read()
    alipay_public_key_string = open("cert/ali_public_key.pem").read()

    alipay = AliPay(
        appid="9021000141672100",
        app_notify_url=None,  # 默认回调 url
        app_private_key_string=app_private_key_string,
        alipay_public_key_string=alipay_public_key_string,
        sign_type="RSA2",  # RSA 或者 RSA2
        debug=False,  # 默认 False
        verbose=False,  # 输出调试数据
        config=AliPayConfig(timeout=15)  # 可选，请求超时时间
    )


    order_obj = Order.objects.filter(id=oid).first()
    goods_info = Goods.objects.filter(id=order_obj.good_id).first()

    order_string = alipay.api_alipay_trade_page_pay(
        # 订单
        # 订单号，使用time模块进行测试设置
        out_trade_no=order_obj.oid,
        total_amount=float(order_obj.price),
        subject=goods_info.title,
        # 支付的结果
        return_url=f"http://127.0.0.1:8000/pay/alipayback/{oid}/",
        # notify_url="https://example.com/notify"  # 可选，不填则使用默认 notify url
    )

    # 使用重定向
    return redirect(f"https://openapi-sandbox.dl.alipaydev.com/gateway.do?{order_string}")





# 支付完返回视图
def alipayback(request, oid):
    """"""
    """支付返回页面"""
    data = request.GET.dict()

    signature = data.pop("sign")
    app_private_key_string = open("cert/ali_private_key.pem").read()
    alipay_public_key_string = open("cert/ali_public_key.pem").read()
    alipay = AliPay(

        appid="9021000141672100",
        app_notify_url=None,  # 默认回调 url
        app_private_key_string=app_private_key_string,
        alipay_public_key_string=alipay_public_key_string,
        sign_type="RSA2",  # RSA 或者 RSA2
        debug=False,  # 默认 False
        verbose=False,  # 输出调试数据
        config=AliPayConfig(timeout=15)  # 可选，请求超时时间
    )

    success = alipay.verify(data, signature)
    print(success, data)
    if success:
        Order.objects.filter(id=oid).update(order_status=2)
        order_obj = Order.objects.filter(id=oid).first()
        insert_sales_data(order_obj)
        inventory = Goods.objects.filter(id=order_obj.good_id).first().inventory
        Goods.objects.filter(id=order_obj.good_id).update(inventory=inventory-order_obj.number)
        return redirect("/order/")
    else:
        return HttpResponse("未知错误！")


def insert_sales_data(order_obj):
    """添加销售数据"""
    Goods_obj = Goods.objects.filter(id=order_obj.good_id).first()
    today = datetime.now()
    date = today.strftime("%Y-%m-%d")
    sales_obj = sales_data.objects.filter(date=date, category=Goods_obj.category).first()
    if not sales_obj:
        sales_data.objects.create(date=date, category=Goods_obj.category, num=order_obj.number, sales=order_obj.price)
    else:
        sales_data.objects.filter(date=date, category=Goods_obj.category).update(num=sales_obj.num+1, sales=sales_obj.sales+order_obj.price)


